package com.example.demo1013.controller;

import com.example.demo1013.entity.Student;
import com.example.demo1013.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;

    // 根据学生ID获取学生信息
    @GetMapping(value = "/getStudentById/{student_id}", produces = "application/json")
    public Student getStudentById(@PathVariable("student_id") String StudentId) {
        System.out.println("student_id=" + StudentId);
        Student student = studentService.getStudentById(StudentId);
        System.out.println("student=" + student);
        return student;
    }


    // 获取所有学生信息
    @GetMapping(value = "/getAllStudents", produces = "application/json")
    public List<Student> getAllStudents() {
        List<Student> students = studentService.getAllStudents();
        return students;
    }

    // 根据条件获取学生信息
    @GetMapping(value = "/getStudentsByCondition/{status}", produces = "application/json")
    public List<Student> getStudentsByCondition(@PathVariable("status") Integer status) {
        System.out.println("status=" + status);
        List<Student> students = studentService.getStudentsByCondition(status);
        return students;
    }

    /**
     * 更新学生信息
     *
     * @param student 学生对象
     * @return 操作结果
     */
    @PostMapping(value = "/updateStudent", produces = "application/json")
    public Map<String, Object> updateStudent(@RequestBody Student student) {
        Map<String, Object> result = new HashMap<>();
        try {
            System.out.println("更新学生信息：student=" + student);
            studentService.updateStudent(student);
            result.put("success", true);
            result.put("message", "学生信息更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "学生信息更新失败：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    // 通过名字搜索学生信息 - 同时支持查询参数和路径变量两种方式
    @GetMapping(value = {"/getStudentsByName", "/getStudentsByName/{name}"}, produces = "application/json")
    public List<Student> getStudentsByName(
            @PathVariable(value = "name", required = false) String nameByPath,
            @RequestParam(value = "name", required = false) String nameByParam) {
        // 优先使用路径变量，如果没有则使用查询参数
        String name = nameByPath != null ? nameByPath : nameByParam;
        System.out.println("搜索名字：name=" + name);
        List<Student> students = studentService.getStudentsByName(name);
        return students;
    }
}